package com.cs.common.interceptor;

import com.cs.common.exception.RegisterException;
import com.cs.common.result.HttpResp;
import com.cs.common.result.ResultCode;
import com.cs.tools.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
import java.util.Objects;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("token");
        if (Objects.isNull(token))
            throw new RegisterException("");
        try {
            String username = JwtUtil.getClaim(token, "username");
            String role = JwtUtil.getClaim(token, "role");
            if(stringRedisTemplate.opsForValue().get(username).equals(token)){
                return true;
            }else{
                return  false;
            }
        } catch (Exception e) { //过期了
            response.setStatus(401);
            return false;
//            String username = (String) JWTUtil.parseToken(token).getPayload().getClaim("username");
//            String role = (String) JWTUtil.parseToken(token).getPayload().getClaim("role");
//            if (stringRedisTemplate.opsForValue().get(username) != null) { //redis的token没有过期
//                String nToken = JwtUtil.createToken(username, tprivs, 1000 * 30);
//                stringRedisTemplate.opsForValue().set(username, nToken, 1, TimeUnit.MINUTES);
//                response.setHeader("token", nToken);
//                return true;
//            } else {
//                return false;
//            }
        }

    }
}
